<template>
	<div class="system-goods-container layout-padding review-list-container">
		<div class="review-list-title-end">
			<!-- <span>评价列表</span> -->
			<div class="title-actions">
				<el-button type="primary" plain circle size="small" @click="refresh">
					<el-icon><Refresh /></el-icon>
				</el-button>
				<el-button type="primary" plain circle size="small" @click="search">
					<el-icon><Search /></el-icon>
				</el-button>
				<el-button type="primary" plain size="small" @click="addComment">添加虚拟评价</el-button>
				<el-button type="danger" plain size="small" @click="recovery">
					<el-icon><Delete /></el-icon>
					回收站
				</el-button>
			</div>
		</div>

		<el-table :data="state.tableData.data" stripe v-loading="state.tableData.loading" style="width: 100%" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column label="商品信息" min-width="150">
				<template #default="scope">
					<div class="product-info">
						<el-image
							:src="STATIC_URL + scope.row.goodsImage"
							class="product-image"
							fit="cover"
							:preview-src-list="[STATIC_URL + scope.row.goodsImage]"
							:initial-index="0"
							preview-teleported
						/>
						<div class="product-details">
							<div>
								{{ scope.row.title }}
							</div>
							<div class="order-number">
								订单号：{{ scope.row.orderId }}
								<el-icon class="copy-icon"><Document /></el-icon>
							</div>
						</div>
					</div>
				</template>
			</el-table-column>

			<el-table-column label="用户信息" width="100">
				<template #default="scope">
					<div class="user-info">
						<el-avatar :src="STATIC_URL + scope.row.avatar" size="medium"></el-avatar>
						<span class="user-type">{{ scope.row.nickname }}</span>
					</div>
				</template>
			</el-table-column>

			<el-table-column label="评价星级" width="180">
				<template #default="scope">
					<el-rate v-model="scope.row.level" disabled show-score text-color="#ff9900" />
				</template>
			</el-table-column>

			<el-table-column prop="reviewImage" label="评价图片">
				<template #default="scope">
					<div v-if="scope.row.images && scope.row.images.length > 0" class="review-images-container">
						<div class="review-image-list">
							<el-image
								v-for="(url, index) in scope.row.images"
								:key="index"
								:src="STATIC_URL + url"
								fit="cover"
								class="review-image-item"
								:preview-src-list="scope.row.images.map((img) => STATIC_URL + img)"
								:initial-index="index"
								preview-teleported
								:hide-on-click-modal="false"
							/>
						</div>
					</div>
				</template>
			</el-table-column>

			<el-table-column prop="content" label="评价内容" min-width="100" />

			<el-table-column prop="createTime" label="评价时间" />

			<el-table-column label="显示状态" width="100">
				<template #default="scope">
					<el-select v-model="scope.row.showd" size="small" @change="(val) => handleStatusChange(val, scope.row)">
						<el-option label="显示" :value="1" />
						<el-option label="隐藏" :value="0" />
					</el-select>
				</template>
			</el-table-column>

			<el-table-column label="评价类型" width="100">
				<template #default="scope">
					<span type="primary" v-if="scope.row.commentType == 0">虚拟评价</span>
					<span type="primary" v-else>正常评价</span>
				</template>
			</el-table-column>

			<el-table-column label="操作" width="120">
				<template #default="scope">
					<el-button link type="primary" size="small" @click="onOpenGoods('edit', scope.row)">编辑</el-button>
					<el-button link type="danger" size="small" @click="onOpenGoods('delete', scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<div class="pagination-container">
			<div class="pagination-info">
				已选择 {{ multipleSelection.length }} 项
				<el-button type="primary" plain size="small" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">删除</el-button>
				<el-button type="primary" plain size="small" :disabled="multipleSelection.length === 0" @click="handleSetStatus(1)">正常</el-button>
				<el-button type="primary" plain size="small" :disabled="multipleSelection.length === 0" @click="handleSetStatus(0)">隐藏</el-button>
			</div>

			<el-pagination
				class="mt15"
				:pager-count="10"
				:page-sizes="[10, 20, 30, 50, 100]"
				v-model:current-page="state.tableData.paging.currentPage"
				background
				v-model:page-size="state.tableData.paging.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.paging.totalCount"
			>
			</el-pagination>
		</div>
		<Dialog ref="DialogRef"></Dialog>
		<CommentDialog ref="CommentDialogRef" @refresh="refresh"></CommentDialog>

		<SearchDialog ref="SearchDialogRef" @handleSearch="handleSearch"></SearchDialog>
	</div>
</template>

<script setup lang="ts">
import { onMounted, reactive, watch, ref, defineAsyncComponent } from 'vue';
import { Delete, Refresh, Search, Document } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { goodsCommentApi } from '/@/api/goods/comment/index';
import msg from '/@/utils/messageUtils';
import { STATIC_URL } from '/@/utils/config';
import _ from 'lodash';
import messageUtils from '/@/utils/messageUtils';
const Dialog = defineAsyncComponent(() => import('./dialog.vue'));
const DialogRef = ref();
const CommentDialog = defineAsyncComponent(() => import('./commentDialog.vue'));
const CommentDialogRef = ref();

const SearchDialog = defineAsyncComponent(() => import('./searchDialog.vue'));
const SearchDialogRef = ref();
const state = reactive({
	catalogData: [] as any,
	isToggle: true,
	choiceIds: [],
	tableData: {
		data: [],
		total: 0,
		loading: false,
		paging: {
			currentPage: 1,
			pageSize: 10,
			totalCount: 0,
			totalPages: 0,
		},
	},
	search: {
		ids: [] as any,
	},
});

const multipleSelection = ref([]);

const search = () => {
	// messageUtils().warn('功能开发中，敬请期待');
	SearchDialogRef.value.handleOpen();
};

const handleSearch = () => {
	messageUtils().warn('处理搜索。。。。。功能开发中，敬请期待');
};

const recovery = () => {
	messageUtils().warn('功能开发中，敬请期待');
};

const handleSelectionChange = (val: any) => {
	// console.log('val: ', val);
	const ids = _.map(val, 'id');
	// console.log('ids: ', ids);
	multipleSelection.value = val;
	state.choiceIds = ids;
};

const onOpenGoods = (type: string, row: any) => {
	if (type === 'delete') {
		ElMessageBox.confirm(`此操作将永久删除商品："${row.title}"评价信息，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(async () => {
			try {
				await goodsCommentApi().delete(row.id);
				msg().success('删除成功');
				onHandleCurrentChange(1);
			} catch (error) {
				msg().error('商品删除失败');
			}
		});
	} else {
		DialogRef.value.onOpen(row.id);
	}
};

const handleSetStatus = async (status: number) => {
	try {
		await goodsCommentApi().batchUpdateShow({
			ids: state.choiceIds,
			showd: status,
		});
		msg().success('操作成功');
		onHandleCurrentChange(1);
	} catch (e) {
		messageUtils().error('操作失败，请稍后重试');
	}
};

const handleBatchDelete = () => {
	try {
		ElMessageBox.confirm(`此操作将永久删除这些评价信息，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(async () => {
			try {
				await goodsCommentApi().batchUpdateShow({ ids: state.choiceIds });
				msg().success('删除成功');
				onHandleCurrentChange(1);
			} catch (error) {
				msg().error('商品删除失败');
			}
		});
	} catch (e) {
		messageUtils().error('操作失败，请重新操作');
	}
};

const addComment = () => {
	CommentDialogRef.value.open();
};

watch(
	() => state.tableData.paging.currentPage,
	(newV, oldv) => {
		console.log(`currentPage, newV: ${newV}, oldV : ${oldv}`);
		onHandleCurrentChange(newV);
	}
);

watch(
	() => state.tableData.paging.pageSize,
	(newV, oldv) => {
		console.log(`pageSize, newV: ${newV}, oldV : ${oldv}`);
		onHandleSizeChange(newV);
	}
);

const refresh = () => {
	onHandleCurrentChange(1);
};

const onHandleSizeChange = (val: number) => {
	state.tableData.paging.pageSize = val;
	state.tableData.paging.currentPage = 1;
	getTableData();
};

const onHandleCurrentChange = (val: number) => {
	state.tableData.paging.currentPage = val;
	getTableData();
};

const handleStatusChange = async (val, row) => {
	console.log('状态修改为', val, row);
	try {
		const { code } = await goodsCommentApi().updateShow({
			id: row.id,
			showd: val,
		});
		if (code != '0') {
			messageUtils().error('操作失败,请稍后重试');
		}
	} catch (e) {
		messageUtils().error('操作失败,请稍后重试');
	}
};

const getTableData = async () => {
	try {
		state.tableData.loading = true;
		const { data } = await goodsCommentApi().search({
			offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
			limit: state.tableData.paging.pageSize,
		});
		state.tableData.data = data.datas;
		state.tableData.paging.currentPage = data.paging.currentPage;
		state.tableData.paging.totalCount = data.paging.totalCount;
		console.log('data： ', data);
	} catch (error) {
		msg().error('查询商品评论列表失败，请稍后重试');
	}
	state.tableData.loading = false;
};

onMounted(() => {
	getTableData();
});
</script>

<style scoped>
.review-list-container {
	background-color: #fff;
	border-radius: 4px;
}

.review-list-header {
	padding: 10px 0;
	border-bottom: 1px solid #ebeef5;
}

.header-tabs {
	display: flex;
	align-items: center;
	position: relative;
}

.tab-item {
	margin-right: 10px;
}

.tab-item.active {
	color: #6366f1;
	border-color: #6366f1;
}

.close-btn {
	position: absolute;
	right: 10px;
}

.review-list-title {
	padding: 15px 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.product-info {
	display: flex;
	align-items: center;
}

.product-image {
	width: 50px;
	height: 50px;
	object-fit: cover;
	margin-right: 10px;
	border-radius: 4px;
}

.product-details {
	display: flex;
	flex-direction: column;
	font-size: 14px;
}

.vip-tag {
	margin-right: 5px;
}

.order-number {
	color: #999;
	font-size: 12px;
	margin-top: 5px;
	display: flex;
	align-items: center;
}

.copy-icon {
	margin-left: 5px;
	cursor: pointer;
	font-size: 12px;
}

.user-info {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.user-type {
	font-size: 12px;
	margin-top: 5px;
	color: #606266;
}

.review-image {
	width: 60px;
	height: 60px;
	border-radius: 4px;
}

.review-images-container {
	width: 100%;
}

.review-image-item {
	width: 50px;
	height: 50px;
}
.review-image-list {
	display: flex;
	gap: 4px;
}
</style>
